package com.haust.community.interceptor;

import com.haust.community.annotation.LoginRequired;
import com.haust.community.utils.HostHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * @Auther: csp1999
 * @Date: 2020/11/24/21:27
 * @Description: 登录请求拦截器,其功能已经交给Spring Security ,所以该拦截器不推荐司用了
 */
@Component
@Deprecated // 声明该接口不推荐使用了，调用时该类上会带有横线
public class LoginRequiredInterceptor implements HandlerInterceptor {

    @Autowired
    private HostHolder hostHolder;

    /**
     * 请求开始前
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response, Object handler) throws Exception {
        // 判断handler 是否是 HandlerMethod 类型
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            // 获取到方法实例
            Method method = handlerMethod.getMethod();
            // 从方法实例中获得其 LoginRequired 注解
            LoginRequired loginRequired = method.getAnnotation(LoginRequired.class);
            // 如果方法实例上标注有 LoginRequired 注解,但 hostHandler中没有 用户信息则拦截
            if (loginRequired != null && hostHolder.getUser() == null) {
                response.sendRedirect(request.getContextPath() + "/login");
                return false;
            }
        }
        return true;
    }
}
